# !/usr/bin/env python3
# -*- coding: utf-8 -*-

'此模块负责接为trunk模块提供辅助'

from lxml import etree
import pandas as pd

from error import MatchingError


def divide(code) -> pd.Series:
    """xml文件项目编码解析

    使用category.xml文件中编码命名规则解析

    Args:
        code: 项目编码

    Returns:
        pd.Series对象

    Raises:
        MatchingError：当编码无法解析时触发
    """
    parser = etree.XMLParser(remove_blank_text=True)
    tree = etree.parse('./rule/category.xml', parser)

    tunnels = tree.xpath('//tunnel/@name')

    if (unit := tree.xpath('//entity[@name="{}"]/text()'.format(code))): # noqa E203 E231
        pass
    else:
        for tunnel in tunnels:
            if code in tunnel:
                unit = tree.xpath('//tunnel[@name="{}"]/text()'.format(tunnel))
                break

    if (individual := tree.xpath('//entity[@name="{}"]/ancestor::individual/@name'.format(code))): # noqa E203 E231
        pass
    else:
        for tunnel in tunnels:
            if code in tunnel:
                individual = tree.xpath('//tunnel[@name="{}"]/ancestor::individual/@name'.format(tunnel)) # noqa E501
                break

    if (project := tree.xpath('//entity[@name="{}"]/ancestor::project/@name'.format(code))): # noqa E203 E231
        pass
    else:
        for tunnel in tunnels:
            if code in tunnel:
                project = tree.xpath('//tunnel[@name="{}"]/ancestor::project/@name'.format(tunnel)) # noqa E501
                break

    if project and individual and unit:
        pass
    else:
        raise MatchingError('编码无法匹配')
    return pd.Series((project[0], individual[0], unit[0]))


def simplify(code) -> pd.Series:
    """xml文件项目编码解析

    简化xxxx-xx-xx日期形式为xxxx-xx

    Args:
        code: xxxx-xx-xx日期字符串形式

    Returns:
        pd.Series对象

    Raises:
        None
    """
    return pd.Series(code[:7])


if __name__ == '__main__':
    print(decipher('zgl-tcl'))
